#!/usr/bin/python
# -*- coding:utf-8 -*-

import Queue
import threading
import time
import sys
import os
import urllib
import re
import codecs
import logging
import ConfigParser

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys  # 导入模拟点击
from base.cvsparser import CvsParser

reload(sys)
sys.setdefaultencoding("utf-8")

# dcap = dict(DesiredCapabilities.PHANTOMJS)  #设置userAgent
# dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (X11; CrOS i686 4319.74.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36")

browser = webdriver.PhantomJS(executable_path='C:\Python27\Scripts\phantomjs.exe')
# browser = webdriver.PhantomJS()
# browser = webdriver.Chrome()
browser.implicitly_wait(60)  ##设置超时时间
browser.set_page_load_timeout(60)  ##设置超时时间
browser.maximize_window()  # 设置全屏

cvs_parser = CvsParser()
file_name = ''

def logConf(is_debug, file_name):
    if is_debug:
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(filename)s+%(lineno)d [%(levelname)s] %(message)s', filemode='w')
    else:
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(filename)s+%(lineno)d [%(levelname)s] %(message)s',
                            filename=file_name,
                            filemode='w')


def getSysTime():
    time_tuple = time.localtime(time.time())  # 获取当前的时间返回一个时间元组
    fmt = '%Y%m%d-%H%M%S'  # 格式化时间
    return time.strftime(fmt, time_tuple)  # 把传入的元组按照格式，输出字符串

curr_time = getSysTime()

def search(url):
	try:
		browser.get(url)
		browser.save_screenshot("open.png")
	except Exception as error:
		logging.error("%s", error)
		return

def writeToFile(var_list):
    try:
        cvs_parser.open(file_name)
        cvs_parser.writeRows(var_list)
        cvs_parser.close()
    except Exception, error:
        logging.error("%s", error)

def gogogo():
    url = "https://tabelog.com/cn/osaka/A2701/A270202/27001286/"

    if len(sys.argv) >= 2:
        url = int(sys.argv[1])

    logging.info("begin: %s", url)

    global file_name
    file_name = "test-" + curr_time + ".csv"
    search(url)

    logging.info("end: %s, save file=%s", url, file_name)

if __name__ == "__main__":
    log_file = "tabelog-" + curr_time + ".log"
    logConf(True, log_file)

    gogogo()

    browser.quit()